package com.yanqu.road.server.gameplayer.module.player;

import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author wpj
 * @Date 2020/10/6
 */
public class PreReduceModule extends GeneralModule {

    Map<Integer, BigInteger> preReduceItemMap;

    public Map<Integer, BigInteger> getPreReduceItemMap() {
        return preReduceItemMap;
    }

    public void setPreReduceItemMap(Map<Integer, BigInteger> preReduceItemMap) {
        this.preReduceItemMap = preReduceItemMap;
    }

    public PreReduceModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        preReduceItemMap = new ConcurrentHashMap<>();
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        return true;
    }

    public void initItem(int itemId) {
        if (!preReduceItemMap.containsKey(itemId)) {
            preReduceItemMap.put(itemId, BigInteger.ZERO);
        }
    }

    public void preReduce(String openCost) {
        Property property = PropertyHelper.parseStringToProperty(openCost);
        preReduce(property);
    }

    /**
     * 预扣除
     * @param property
     */
    public void preReduce(Property property) {
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            initItem(entry.getKey());
            preReduceItemMap.put(entry.getKey(), preReduceItemMap.get(entry.getKey()).subtract(entry.getValue()));
        }
    }


    public void restorePreReduce(String openCost) {
        Property property = PropertyHelper.parseStringToProperty(openCost);
        restorePreReduce(property);
    }

    /**
     * 取消预扣除
     * @param property
     */
    public void restorePreReduce(Property property) {
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            initItem(entry.getKey());
            preReduceItemMap.put(entry.getKey(), preReduceItemMap.get(entry.getKey()).add(entry.getValue()));
            if (preReduceItemMap.get(entry.getKey()).compareTo(BigInteger.ZERO) > 0) {
                // 预扣除不允许值大于0
                preReduceItemMap.put(entry.getKey(), BigInteger.ZERO);
            }
        }
    }
}
